<!--
 * @Author: xiezhiquan3878
 * @Date: 2024-06-21 17:21:51
 * @LastEditors: zhayang 1063975710@qq.com
 * @LastEditTime: 2024-07-04 22:52:04
 * @FilePath: \heart-backed\src\views\banner\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="context">
    <template v-if="flag">
      <vue-draggable-resizable
        v-for="(item, index) in data"
        :key="`${item.type}_${item.i}`"
        :ref="`drag_${index}`"
        is-draggable
        :parentLimitation="true"
        aspect-ratio
        is-resizable
        :w="item.w"
        :h="item.h"
        :y="item.y"
        :x="item.x"
        :minh="20"
        :minw="20"
        class="drag-item"
        @dragging="onDrag"
        @resizing="onResize"
        @activated="onActivated(index)"
        @deactivated="onDeactivated"
      >
        <div
          v-if="item.type === 'txt'"
          contenteditable="true"
          :style="`font-size:${item.props.size}px;color: ${item.props.color};text-align:${item.props.align}`"
          @input="changeText($event, item, index)"
        >
          {{ item.context }}
        </div>
        <div
          v-if="item.type === 'img'"
          style="overflow: hidden"
          class="w-100% h-100%"
        >
          <img
            draggable="false"
            class="w-100% h-100%"
            :src="item.src"
            :alt="item.src"
          />
        </div>
      </vue-draggable-resizable>
    </template>
  </div>
</template>

<script>
import VueDraggableResizable from 'vue-drag-resize'
export default {
  name: 'Draggable',
  components: {
    VueDraggableResizable
  },
  props: {
    data: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      flag: false,
      currentI: null // 当前激活下标
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.flag = true
    })
  },
  methods: {
    changeText(e, item, i) {
      this.$emit('changeTxt', e.target.innerHTML, i)
    },
    onDeactivated() {
      // 失去激活
      this.currnetI = null
    },
    onActivated(i) {
      // 激活
      this.currentI = i
    },
    onDrag({ top, left, width, height }) {
      // 移动
      if (this.currentI || this.currentI === 0) {
        this.$emit('updata', this.currentI, left, top)
      }
    },
    onResize({ top, left, width, height }) {
      if (this.currentI || this.currentI === 0) {
        if (width > 0 && height > 0) {
          this.$emit('updata', this.currentI, left, top, width, height)
        }
      }
    }
  }
}
</script>

<style scoped lang="scss">
// @import 'vue-draggable-resizable/style.css';
.context {
  position: relative;
}
img {
  user-select: none;
  pointer-events: none;
}
::v-deep .drag-item {
  border: 1px dashed #04d1b8;
  .handle {
    background: #04d1b8;
    border: 1px solid #04d1b8;
  }
}
</style>
